package no.uib.kwikktaim.gui.actionlisteners;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;


import no.uib.kwikktaim.gui.KeyFrames;
import no.uib.kwikktaim.gui.MainWindow;
import no.uib.kwikktaim.utils.ByteConvertor;

/**
 * Listens for mouse clicks, and loads images from cache if exists
 */
public class KeyFramesListener implements ActionListener {
	MainWindow mw;
	public KeyFramesListener(MainWindow mw) {
		this.mw = mw;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(mw.getPlayer().isVideo()) {
			if(mw.kf == null) {

				// Ser om vi kan deserialisere et objekt istedenfor aa regne ut keyframsene igjen!
				ArrayList<Image> isIt = deSerialize("cache"+ File.separator + Math.abs(mw.getPlayer().getCurrentURL().hashCode()) + ".srz");

				if(isIt == null)
					mw.kf = new KeyFrames(mw);
				else {
					mw.kf = new KeyFrames(isIt,mw);
				}

			}
			else
				mw.kf.setVisible(true);
		}
		else
			JOptionPane.showMessageDialog(mw, "This is not a video, so keyframes is not supported", "Not a video ERROR! SOS! 404!", JOptionPane.INFORMATION_MESSAGE);

	}

	/**
	 * Tries to read a serialized version of the keyframes of this movie
	 * @param name name of the file
	 * @return The Keyframes window (if it exists)
	 */
    @SuppressWarnings("unchecked")
	private ArrayList<Image> deSerialize(String name) {
    	ArrayList<Image> res = new ArrayList<Image>();
    	ArrayList<Byte[]> a = null;
        try {
            FileInputStream fis = new FileInputStream(name);
            ObjectInputStream ois;
            ois = new ObjectInputStream(fis);
            try {
                a = (ArrayList<Byte[]>)ois.readObject();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
            ois.close();
        } catch (IOException ex) {
        	return null;
        }

        for (Byte[] bytes : a) {
        	ByteArrayInputStream inStr = new ByteArrayInputStream(ByteConvertor.byteToByte(bytes));
        	try {
        		res.add(ImageIO.read(inStr));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
        return res;
    }
}
